package com.back.campus_back.controller;

import com.alibaba.fastjson.JSONObject;
import com.back.campus_back.domain.Goods;
import com.back.campus_back.domain.GoodsCategory;
import com.back.campus_back.domain.User;
import com.back.campus_back.service.impl.UserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhenzi.sms.ZhenziSmsClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-04-17
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户控制类")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    /*
    * apiUrl：榛子云平台提供的个人开发访问连接
    * appId：榛子云平台提供的短信id
    * appSecret：榛子云平台提供的短信密钥
    * */
    String apiUrl = "https://sms_developer.zhenzikj.com";
    String appId = "108947";
    String appSecret = "472c6cc7-fd09-4132-a1c0-3fe0a803dc67";

    //swagger-ui中，编写短信接口测试方法
    @GetMapping("/sendCode/{phoneNum}")
    public String getCode(@PathVariable("phoneNum") String phoneNum)throws Exception {
            JSONObject json = null;
            //自定义随机生成验证码
            String code = String.valueOf(new Random().nextInt(999999));
            //创建榛子云短信平台接口的对象
            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
            Map<String, Object> params = new HashMap<String, Object>();
            //输入模板的对应的参数
            params.put("number", phoneNum);
            params.put("templateId", "5072");
            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "3分钟";
            params.put("templateParams", templateParams);
            //模板参数写完，进行短信发送
            String result = client.send(params);
            //将短信发送的结果返回值进行json数据封装
            json = JSONObject.parseObject(result);
            if (json.getIntValue("code") != 0) {//只要code不为0，则发送短信失败！
                return "发送短信失败";
            }
            return code;
    }

    /*
    *前端短信验证操作:
    *1.接收前端发过来的电话号码；
    *2.进行短信模板参数的编写。
    *3.进行短信发送
    *4.短信发送的结果返回值中，只要code不为0，则短信发送失败
    *5.将短信发送的结果返回值进行json封装
    *6.根据code的值进行不同的操作返回给前端进行不同的操作*/
    @PostMapping("/sendCode")
    public String getCode(@RequestBody Map<String,String> PhoneNum)throws Exception {
            JSONObject json = null;
            //自定义随机生成验证码
            String code = String.valueOf(new Random().nextInt(999999));
            //创建榛子云短信平台接口的对象
            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
            Map<String, Object> params = new HashMap<String, Object>();
            //输入模板的对应的参数
            params.put("number", PhoneNum.get("PhoneNumber"));
            params.put("templateId","5072");
            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "3分钟";
            params.put("templateParams", templateParams);
            System.out.println("传入的手机号为："+PhoneNum.get("PhoneNumber"));
            //模板参数编写完，进行短信发送
            String result = client.send(params);
            //将短信发送的结果返回值进行json数据封装
            json = JSONObject.parseObject(result);
            if (json.getIntValue("code") != 0) {//只要code不为0，则发送短信失败！
               return  "发送短信失败";
            }else {
            return code;
            }
    }

    /*
     * 根据用户的电话号码查询用户是否存在，进行登录
     * */
    @PostMapping("/SMSLogin")
    public User SMSLogin(@RequestBody Map<String,String> PhoneNum){
      return userService.SMSLogin(PhoneNum.get("phoneNumber"));
    }


    /*
     * 根据查询用户的id和密码查询用户是否存在，进行登录
     * */
    @GetMapping("/login/{userName}/{password}")
    public User login(@PathVariable("userName") String userName, @PathVariable("password")String user_password){
       return userService.login(userName,user_password);
    }


    /*
     * 根据查询用户名来查询用户是否存在，进行登录
     * */
    @PostMapping("/findUserName")
    public User findUserName(@RequestBody Map<String,String> user){
        return userService.findUserName(user.get("userName"));
    }


    /*
     * 查询全部用户
     * */
    @ApiOperation("查询全部用户")
    @GetMapping("/findAllUser")
    public List<User> findAllUser(){
        return userService.findAllUser();
    }

    /*
     *模糊查询
     * */
    @ApiOperation("模糊查询用户")
    @GetMapping("/findAllUser/{current}/{size}/{username}")
    public IPage<User> findAll(@PathVariable("current") Integer current, @PathVariable("size") Integer size,@PathVariable(required = false)String username){
        return userService.findAllUser(current,size,username);
    }

    //分页查询用户
    @ApiOperation("分页查询用户")
    @GetMapping("/findAllUser/{current}/{size}")
    public IPage<User> findByLink(@PathVariable("current") Integer current, @PathVariable("size") Integer size){
        return userService.findByUser(current,size);
    }

    /*
     * 注册用户操作：
     * 获取前端发来的用户名和密码进行注册
     * */
    @ApiOperation("注册用户")
    @PostMapping("/register")
    public String registerUser(@RequestBody Map<String,String> user){
        return userService.registerUser(user.get("userName"),user.get("password"));
    }


    /*
     * 根据id查询用户
     * */
    @ApiOperation("根据id查询用户")
    @PostMapping("/findUserById")
    public User findBookById(@RequestBody Map<String,Integer> user) {
        return userService.findUserById(user.get("userId"));
    }

    /*
     * 更新用户信息
     * */
    @ApiOperation("更新用户信息")
    @PostMapping("/updateUser")
    public User updateUserInfo(@RequestBody  User user){
      System.out.println("user:"+user);
        return userService.updateUserInfo(user);
    }

    /*
     * 根据id删除用户
     * */
    @ApiOperation("根据id删除用户")
    @GetMapping("/deleteUserById/{user_id}")
    public String deleteUserById(@PathVariable("user_id")Integer user_id) {
        return userService.deleteUserById(user_id);
    }

    //更新用户头像
    @RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
    public User uploadImg(@RequestBody Map<String,String>  uploadImg)  throws IOException {

      String baseValue = uploadImg.get("data").replaceAll(" ", "+");
      // Base64解码
      BASE64Decoder decoder = new BASE64Decoder();
      byte[] bytes = decoder.decodeBuffer(baseValue.replace("data:image/png;base64,", ""));
      for (int i = 0; i < bytes.length; ++i) {
        if (bytes[i] < 0) {// 调整异常数据
          bytes[i] += 256;
        }
      }


      //获取当前项目存放上传图片的指定文件夹
      String path =  this.getClass().getClassLoader().getResource("static/imgs/headPic").getPath();
      //删除开头的/
      String path1 = path.substring(1, path.length());
      System.out.println("resource:"+path1);
      //指定上传图片的格式
      String PhotoImgpath =path1+"/"+uploadImg.get("fileName");
      //这是存放上传图片的文件夹
      File uploads = new File(path1);
      // 如果文件夹不存在则创建
      if (!uploads.exists() && !uploads.isDirectory()) {
        uploads.mkdirs();
      }
      //获取上传图片时的名字。
      String fileName = uploadImg.get("fileName");
      try {
        // 将上传的文件写入指定文件.
        OutputStream out = new FileOutputStream(PhotoImgpath);
        out.write(bytes);
        out.flush();
        out.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      // 将上传的图片保存的路径在数据库中保存
      String tmp_path = "../imgs/headPic/"+fileName;
      int userId= Integer.parseInt(uploadImg.get("userId"));
      System.out.println("拿到了userid:");
      User userResult= userService.uploadImg(tmp_path,userId);
      System.out.println("userResult"+userResult);
      if (userResult!=null) {
        return userResult;
      } else {
        return null;
      }
    }
}

